import config from '../config.js';

/**
 * 打印请求日志
 * @param {object} obj 
 */
function _log(obj) {
  if (config.env === 'dev' || config.env === 'test') {
    console.log('request: ' + config.api + obj.url);
    console.log('method: ' + (obj.method || 'GET'));
    console.log('data: ' + JSON.stringify(obj.data, null, '\t'));
    console.log('result: ');
    console.log(obj.res);
    console.log('-------------------------------------------------------');
  }
}

/**
 * 请求接口封装
 * @param {object} options 
 * --@param {string} url
 * --@param {string} method
 * --@param {object} data
 * --@param {string} loadTitle 加载提示语
 * --@param {boolean} isError 是否需要手动处理错误
 */
function service(options) {
  return new Promise((resolve, reject) => {
    if (options.loadTitle) {
      wx.showLoading({
        title: options.loadTitle,
        mask: true
      })
    }
    wx.request({
      url: config.api + options.url,
      method: options.method || 'GET',
      data: options.data || {},
      header: {
        "content-type": "application/x-www-form-urlencoded",
        "token": getApp().globalData.token,
        "brand": getApp().globalData.systemInfo.brand,
        "systemInfo": JSON.stringify(getApp().globalData.systemInfo)
      },
      success: res => {
        _log({
          ...options,
          res: res.data
        });
        const {
          statusCode,
          data
        } = res;
        if (statusCode === 200 && data.code === '00000') {
          resolve(data.data);
        } else if (data.code === 'B0311') {
          // token 失效
          getApp().globalData.isLogin = false;
          reject();
        } else if (statusCode === 500) {
          wx.showToast({
            title: '服务器出现异常，请联系管理员',
            icon: 'none',
            duration: 3000
          });
        } else {
          if (options.isError) {
            reject(data);
          } else {
            wx.showToast({
              title: data.message ? data.message : '未知错误',
              icon: 'none',   
              duration: 3000
            });
          }
        }
      },
      fail: err => {
        _log({
          ...options,
          res: err
        });
        wx.showToast({
          title: '未知错误',
          icon: 'none',
          duration: 3000
        });
        reject(err);
      },
      complete: () => {
        if (options.loadTitle) wx.hideLoading();
      }
    })
  })
}

export default service